package com.rr.mymoney.jsf;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;

import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.web.WebAttributes;

public class LoginErrorPhaseListener implements PhaseListener {
    private static final long serialVersionUID = -1216620620302322995L;

    public void beforePhase(PhaseEvent event) {
	Exception e = (Exception) FacesContext.getCurrentInstance().getExternalContext().getSessionMap()
		.get(WebAttributes.AUTHENTICATION_EXCEPTION);

	if (e instanceof BadCredentialsException || e instanceof AuthenticationServiceException) {
	    FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put(WebAttributes.AUTHENTICATION_EXCEPTION, null);
	    // FacesUtils.addErrorMessage("Username or password not valid.");
	    FacesContext.getCurrentInstance().addMessage(null,
		    new FacesMessage(FacesMessage.SEVERITY_ERROR, "Username or password not valid.", ""));
	}
    }

    public void afterPhase(final PhaseEvent event) {
    }

    public PhaseId getPhaseId() {
	return PhaseId.RENDER_RESPONSE;
    }

}